﻿using GBT_Tool_v4._0;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ExportMealToExcel
{
    public partial class Login : Form
    {
        private Logger logger = LogManager.GetCurrentClassLogger();
        bool isLogin = false;
        Win32 w32 = new Win32();
        HttpRequest hr = new HttpRequest();
        Encryption ency = new Encryption();
        Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

        public Login()
        {
            InitializeComponent();
        }

        //protected override CreateParams CreateParams
        //{
        //    get
        //    {
        //        CreateParams cp = base.CreateParams;
        //        cp.ExStyle |= 0x00080000;  //  WS_EX_LAYERED 扩展样式
        //        return cp;
        //    }
        //}

        public string message { get; set; }

        public string username { get; set; }

        public string number { get; set; }

        public string password { get; set; }

        /// <summary>
        /// 是否记住密码
        /// </summary>
        public string remember { get; set; }

        public void SetBitmap(Bitmap bitmap, byte opacity)
        {
            if (bitmap.PixelFormat != PixelFormat.Format32bppArgb)
                throw new ApplicationException("位图必须是32位包含alpha 通道");

            IntPtr screenDc = Win32.GetDC(IntPtr.Zero);
            IntPtr memDc = Win32.CreateCompatibleDC(screenDc);
            IntPtr hBitmap = IntPtr.Zero;
            IntPtr oldBitmap = IntPtr.Zero;

            try
            {
                hBitmap = bitmap.GetHbitmap(Color.FromArgb(0));   // 创建GDI位图句柄，效率较低
                oldBitmap = Win32.SelectObject(memDc, hBitmap);

                Win32.Size size = new Win32.Size(bitmap.Width, bitmap.Height);
                Win32.Point pointSource = new Win32.Point(0, 0);
                Win32.Point topPos = new Win32.Point(Left, Top);
                Win32.BLENDFUNCTION blend = new Win32.BLENDFUNCTION();
                blend.BlendOp = Win32.AC_SRC_OVER;
                blend.BlendFlags = 0;
                blend.SourceConstantAlpha = opacity;
                blend.AlphaFormat = Win32.AC_SRC_ALPHA;

                Win32.UpdateLayeredWindow(Handle, screenDc, ref topPos, ref size, memDc, ref pointSource, 0, ref blend, Win32.ULW_ALPHA);
            }
            finally
            {
                Win32.ReleaseDC(IntPtr.Zero, screenDc);
                if (hBitmap != IntPtr.Zero)
                {
                    Win32.SelectObject(memDc, oldBitmap);

                    Win32.DeleteObject(hBitmap);
                }
                Win32.DeleteDC(memDc);
            }
        }
        
        private void Login_Load(object sender, EventArgs e)
        {
            //SetBitmap(null, 100);
            number = ConfigurationManager.AppSettings["number"];
            password = ConfigurationManager.AppSettings["password"];
            remember = ConfigurationManager.AppSettings["remember"];
            txtUserName.Text = number;
            txtPassword.Text = password;

            //判断是否勾选记住密码
            if (string.IsNullOrEmpty(remember))
            {
                cbIsRememb.Checked = false;
            }
            else
            {
                cbIsRememb.Checked = true;
            }
        }

        private void loginVerify()
        {
            try
            {
                JObject param = new JObject();
                param["Number"] = number;
                param["password"] = password;
                param["districtID"] = Program.districtID;

                logger.Info(param);
                string requestJson = JsonConvert.SerializeObject(param);
                string resultJson = hr.GBTPost(Program.host_url + "gbt/UserVerify/PasswordVerify", requestJson);
                JObject joResult = JObject.Parse(resultJson);
                JObject joResultRoot = (JObject)joResult["root"];
                logger.Info(joResultRoot);
                JArray jaResult = (JArray)joResultRoot["data"];
                if (lblMessage.InvokeRequired)
                {
                    Action<object> actionDelegate = (o) =>
                    {
                        bool state = (bool)joResultRoot["state"];
                        if (state)
                        {
                            lblMessage.ForeColor = Color.Black;
                        }
                        else {
                            lblMessage.ForeColor = Color.Red;
                            //登录失败时 清空配置文件
                            number = "";
                            
                            cfa.AppSettings.Settings["password"].Value = "";
                            cfa.Save();
                        }

                        lblMessage.Text = (string)joResultRoot["message"];
                    };
                    lblMessage.BeginInvoke(actionDelegate, "");
                }
                if (jaResult.Count > 0)
                {
                    //验证成功则关闭登陆页面
                    message = (string)joResultRoot["message"];
                    username = (string)jaResult[0]["Name"];
                    isLogin = true;
                    DialogResult = DialogResult.OK;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            number = txtUserName.Text;
            //password = Encryption.Get_MD5(txtPassword.Text);

            //不存在密码信息 则使用用户输入的密码进行验证
            if (string.IsNullOrWhiteSpace(password))
            {
                password = Encryption.Get_MD5(txtPassword.Text);
            }
            
            cfa.AppSettings.Settings["number"].Value = number;
            //在勾选记住密码的情况下 才会保存密码
            if (!string.IsNullOrEmpty(remember))
            {
                cbIsRememb.Checked = true;

                cfa.AppSettings.Settings["password"].Value = password;
            }
            else
            {
                //取消勾选记住密码时 情况配置文件
                cfa.AppSettings.Settings["password"].Value = "";
            }
            cfa.Save();

            lblMessage.ForeColor = Color.Black;
            lblMessage.Text = "就绪";

            //验证登录信息
            Thread t = new Thread(loginVerify);
            t.Start();
        }

        private void Login_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (!isLogin)
            {
                Application.Exit();
            }
        }

        private void llbModifyPassword_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ModifyPassword mp = new ModifyPassword();
            if (mp.ShowDialog() == DialogResult.OK)
            {
                lblMessage.Text = mp.message;
            }
        }

        private void cbIsRememb_CheckedChanged(object sender, EventArgs e)
        {
            if (cbIsRememb.Checked)
            {
                remember = "true";
                
                cfa.AppSettings.Settings["remember"].Value = remember;
                cfa.Save();
            }
            else
            {
                remember = "";
                //取消勾选记住密码时 同步清空配置文件
                cfa.AppSettings.Settings["remember"].Value = "";
                cfa.AppSettings.Settings["number"].Value = "";
                cfa.AppSettings.Settings["password"].Value = "";
                cfa.Save();
            }
        }

        private void txtUserName_TextChanged(object sender, EventArgs e)
        {
            number = txtUserName.Text;
        }

        private void txtPassword_TextChanged(object sender, EventArgs e)
        {
            //用户手动输入密码 则清空密码 登陆时会自动获取密码框的密码 
            if (password != txtPassword.Text)//防止在初始化密码的时候 清空密码变量
            {
                password = "";
            }
        }
    }
}
